package com.hulk.dryad.admin.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hulk.dryad.admin.api.vo.SysUserVO;
import com.hulk.dryad.admin.api.dto.UserInfoDTO;
import com.hulk.dryad.admin.mapstruct.UserInfoStruct;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.constant.enums.DelFlag;
import com.hulk.dryad.common.constant.enums.LockFlag;
import com.hulk.dryad.common.util.DesensitizedUtil;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.persistence.entity.UserInfoModel;
import com.hulk.dryad.admin.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author kim
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminSysUserDetailsServiceImpl implements AdminSysUserDetailsService {

	private final SysUserService sysUserService;


	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {

		SysUserModel user = sysUserService.getOne(Wrappers.<SysUserModel>query().lambda().eq(SysUserModel::getUsername, username));
		if (user == null|| DelFlag.Y.getValue().equals(user.getDelFlag())) {
			throw new UsernameNotFoundException(BEC.E_2015.toString());
		}
		if(LockFlag.Y.getValue().equals(user.getLockFlag())){
			throw new UsernameNotFoundException(BEC.E_2028.toString());
		}
		UserInfoModel userInfoModel = sysUserService.findUserInfo(user);
		UserInfoDTO userInfoDTO = UserInfoStruct.INSTANCE.from(userInfoModel);
		UserDetails userDetails = getUserDetails(userInfoDTO);
		return userDetails;
	}

	/**
	 * 构建userDetails
	 *
	 * @param info 用户信息
	 * @return
	 */
	private UserDetails getUserDetails(UserInfoDTO info) {

		Set<String> dbAuthsSet = new HashSet<>();
		if (ArrayUtil.isNotEmpty(info.getRoles())) {
//			Arrays.stream(info.getRoleCodes()).forEach(roleCode -> {
//				/* 获取用户组,此处以角色标识作为组名 */
//				/* Activiti拾取适用*/
//				dbAuthsSet.add(roleCode);
//			});
			Arrays.stream(info.getRoles()).forEach(roleId -> {
				/* 获取角色*/
				dbAuthsSet.add(SecurityConstants.ROLE + roleId);
			});
			/* 获取资源*/
			dbAuthsSet.addAll(Lists.newArrayList(info.getPermissions()));
		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUserVO user = info.getSysUserVO();

		HttpServletRequest request = WebUtils.getRequest();
		String tenantId = request.getHeader(CommonConstants.TENANT_ID);
		if (StrUtil.isBlank(tenantId)) {
			tenantId = request.getParameter(CommonConstants.TENANT_ID);
		}
		user.setTenantId(tenantId);
		boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
		String totp =user.getTotp();
		totp = DesensitizedUtil.desValue(totp,4,4,"*");


		/* 构造security用户*/
		return new AdminUser(user.getUserId(), user.getDeptId(), user.getPhone(),  user.getAvatar(),info.getPosts(),  user.getTenantId(),user.getRootFlag(),totp, user.getUsername(),
				SecurityConstants.BCRYPT + user.getPassword(), enabled, true, true,
				!CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
	}

}
